package thread;

import java.util.Scanner;

public class ThreadDemo20 {
    private volatile static int flag=0;

    public static void main(String[] args) {
        Thread t1=new Thread(()->{
            while(flag==0){
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);//一般来说,可以通过减缓时间来解决内存可见性问题,但是这个问题总是不可控制的,因此我们提供了volatile这个关键字;
                    //1.强制cpu只能从工作内存中读取数据
                    //2.禁止指令重排序
                }
            }
            System.out.println("线程结束");
        });
        Thread t2=new Thread(()->{
            Scanner scanner=new Scanner(System.in);
            flag=scanner.nextInt();
        });
        t1.start();
        t2.start();
    }
}
